<template>
  <div :id="id" style="width: 100%;height: 400px;"></div>
</template>

<script>
import * as echarts from "echarts";

export default {
  data() {
    return {
      myChart: null
    };
  },
  props: {
    id: {
      type: String,
      default: 'bar'
    },
    title: {
      type: String,
      default: ''
    },
    initData: {
      type: Array,
      default: () => []
    }
    
  },
  mounted() {
    this.initBar();
  },
  watch: {
    initData: {
      handler() {
        this.initBar();
      },
    },
  },
  methods: {
    initBar() {
      const _this = this
      const chartDom = document.getElementById(this.id);
      this.myChart = echarts.init(chartDom);
      this.myChart.showLoading();

      const keys = [];
      const dataList = [];
      this.initData.forEach(item => {
        keys.push(item.name)
        dataList.push(item.count)
      })

      let option = {
        title: {
          text: this.title,
          left: 'center',
          top: 'center',
          textStyle: {
            color: '#e4e4e4',
            fontSize: '50',
          },
          zlevel: -1
        },
        color: ['#d01951'],
        tooltip: {
          trigger: "axis",
          axisPointer: {
            type: "shadow",
          },
        },
        grid: {
          left: "1%",
          right: "1%",
          bottom: "1%",
          containLabel: true,
        },
        xAxis: [
          {
            type: "category",
            data: keys,
            axisTick: {
              alignWithLabel: true,
            },
            axisTick: {
              show: false
            },
            axisLine: {
              show: false
            },
            axisLabel: {
              interval:0,
              rotate:40
            }
          },
        ],
        yAxis: [
          {
            type: "value",
            show: false
          },
        ],
        series: [
          {
            type: "bar",
            barWidth: "15%",
            data: dataList,
            label: {
              show: true,
              position: 'top',
              valueAnimation: true
            }
          },
        ],
      };

      option && this.myChart.setOption(option);
      this.myChart.hideLoading();
      window.addEventListener("resize", function() {
        _this.myChart.resize();
      });
    },
  },
  beforeDestroy() {
    if (this.myChart) {
      this.myChart.clear();
    }
  }
};
</script>

<style lang="less" scoped>
</style> 
